package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * app端登录功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.正常登录（手机号+密码登录）
        if(!StringUtils.isBlank(dto.getPhone())&&!StringUtils.isBlank(dto.getPassword())){
            //不为空查询对象
            LambdaQueryWrapper<ApUser> lqw =new LambdaQueryWrapper<>();
            lqw.eq(ApUser::getPhone,dto.getPhone());

            ApUser apUser = this.getOne(lqw);
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名不存在");
            }
            //用户名存在对比密码
            String slat= apUser.getSalt();
            String password =dto.getPassword();
            //加盐加密
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((password + slat).getBytes());
            if(!apUser.getPassword().equals(md5DigestAsHex)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //密码正确存token存返回token
            Map<String,Object> map =new HashMap<>();
            map.put("token",AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
            //为空的话是游客登录
            Map<String,Object> map =new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return  ResponseResult.okResult(map);
        }
    }
}
